package com.basic.modules.nykf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.common.utils.*;
import com.basic.modules.nykf.dao.ZzhFpKfDao;
import com.basic.modules.nykf.entity.JxSjEntity;
import com.basic.modules.nykf.entity.ZzhFpGsEntity;
import com.basic.modules.nykf.entity.ZzhFpKfEntity;
import com.basic.modules.nykf.service.JxSjService;
import com.basic.modules.nykf.service.ZzhFpGsService;
import com.basic.modules.nykf.service.ZzhFpKfService;
import com.basic.modules.sys.entity.SysUserEntity;
import com.basic.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ZzhFpKfServiceImpl extends ServiceImpl<ZzhFpKfDao, ZzhFpKfEntity> implements ZzhFpKfService {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    ZzhFpGsService zzhFpGsService;

    @Autowired
    JxSjService jxSjService;

    @Override
    public PageUtils getZzhFpkfList(ParamsModel<Map> params) {
        IPage<Map> page = new Query<Map>().getPage(BeanUtil.beanToMap(params.getPage()));
        IPage<Map> zzhFpkfList = baseMapper.getZzhFpkfList(page, params.getCondition());
        return new PageUtils(zzhFpkfList);
    }

    @Override
    public List<Map> getKfList(Map map) {
        // 先找到这个公司的人
        String companyNo = map.get("companyNo").toString();
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserEntity::getCompanyNo, companyNo);
        List<String> postNos = new ArrayList<>();
        postNos.add("客服");
        postNos.add("客服部经理");
        postNos.add("客服部副经理");
        postNos.add("客服部主管");
        queryWrapper.lambda().in(SysUserEntity::getPostNo, postNos);
        List<SysUserEntity> list = sysUserService.list(queryWrapper);

        List<Map> list1 = new ArrayList<>();
        // 继续分配规则过滤
        for (SysUserEntity sysUserEntity : list) {
            Map map1 = new HashMap();
            map1.put("label", sysUserEntity.getName() + "-" + sysUserEntity.getFlowerName());
            map1.put("value", sysUserEntity.getUserId());
            list1.add(map1);
        }
        return list1;
    }

    @Override
    public R postZzhFpkf(ZzhFpKfEntity zzhFpKfEntity) {
        // 校验分配公司数据
        // 如果分配公司的结束日期是2188,分配客服的开始日期及结束日期必须大于等于分配公司的开始日期
        // 如果分配公司的结束日期不是2188,分配的开始日期及结束日期都必须大于等于分配公司的开始日期且小于等于结束日期
        Long fpGsId = zzhFpKfEntity.getFpGsId();
        ZzhFpGsEntity zzhFpGsObj = zzhFpGsService.getById(fpGsId);

        Date fpgsKsrq = zzhFpGsObj.getKsrq();
        Date fpgsJsrq = zzhFpGsObj.getJsrq();
        Date fpkfKsrq = zzhFpKfEntity.getKsrq();
        Date fpkfJsrq = zzhFpKfEntity.getJsrq();
        Long kfUserId = zzhFpKfEntity.getKfUserId();
        boolean isPermanent = fpkfJsrq.getTime() == 6879398400000L; // 判断是否为永久(2188年)

        // 校验1: 结束日期不能小于开始日期(除非结束日期是永久)
        if (fpkfJsrq.compareTo(fpkfKsrq) < 0) {
            return R.error("结束日期不能小于开始日期!");
        }

        if (fpkfKsrq.compareTo(fpgsKsrq) < 0) {
            return R.error("分配客服的开始日期不得小于分配公司的开始日期");
        }

        if (fpkfJsrq.compareTo(fpgsKsrq) < 0) {
            return R.error("分配客服的结束日期不得小于分配公司的开始日期");
        }

        if (fpgsJsrq.getTime() != 6879398400000L) {
            if (fpkfKsrq.compareTo(fpgsJsrq) > 0) {
                return R.error("分配客服的开始日期不得大于分配公司的结束日期");
            }

            if (fpkfJsrq.compareTo(fpgsJsrq) > 0) {
                return R.error("分配客服的结束日期不得大于分配公司的结束日期");
            }
        }

        // 校验4: 检查时间段是否与历史分配重叠
        QueryWrapper<ZzhFpKfEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZzhFpKfEntity::getFpGsId, fpGsId);
        List<ZzhFpKfEntity> fpKfList = this.list(queryWrapper);

        for (ZzhFpKfEntity existingKf : fpKfList) {
            Date existingKsrq = existingKf.getKsrq();
            Date existingJsrq = existingKf.getJsrq();
            boolean existingIsPermanent = existingJsrq.getTime() == 6879398400000L;

            if (isPermanent) {
                // 分配=2188 历史!=2188
                if (!existingIsPermanent) {
                    if (fpkfKsrq.compareTo(existingJsrq) <= 0)
                        return R.error("分配时间段与历史分配时间重叠!");
                }
                // 分配=2188 历史=2188
                else {
                    if (fpkfKsrq.compareTo(existingKsrq) <= 0)
                        return R.error("分配时间段与历史分配时间重叠!");
                }
            } else {
                // 分配!=2188  历史!=2188
                if (!existingIsPermanent) {
                    if (fpkfKsrq.compareTo(existingJsrq) <= 0 &&
                            fpkfJsrq.compareTo(existingKsrq) >= 0) {
                        return R.error("分配时间段与历史分配时间重叠!");
                    }
                }
                // 分配!=2188  历史=2188
                else {
                    if (fpkfKsrq.compareTo(existingKsrq) == 0 || fpkfJsrq.compareTo(existingKsrq) == 0) {
                        return R.error("分配时间段与历史分配时间重叠!");
                    }
                }
            }
        }

        for (ZzhFpKfEntity existingKf : fpKfList) {
            if (existingKf.getJsrq().getTime() == 6879398400000L) {
                if (existingKf.getKsrq().compareTo(fpkfKsrq) < 0) {
                    // 将历史永久记录的结束日期修改为当前开始日期的前一天
                    existingKf.setJsrq(DateUtils.addDateDays(fpkfKsrq, -1));
                    this.updateById(existingKf);
                }
            }
        }
        Long userId = CommonUtils.getUserId();
        zzhFpKfEntity.setCreateUserId(userId);
        boolean save = this.save(zzhFpKfEntity);

        // 客服分配完成后,同时同步绩效数据
        if(save){
            UpdateWrapper<JxSjEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda()
                    .ge(JxSjEntity::getDate, fpkfKsrq)
                    .le(JxSjEntity::getDate, fpkfJsrq)
                    .set(JxSjEntity::getFpKfId, zzhFpKfEntity.getFpKfId());
            jxSjService.update(updateWrapper);
        }
        return R.ok();
    }

    @Override
    public R postFpkfRevoke(ZzhFpKfEntity zzhFpKfEntity) {
        // 后期会加入该客服是否产生服务数据,如果产生了服务数据则不允许撤销
        Long fpKfId = zzhFpKfEntity.getFpKfId();
        boolean removeFpKf = this.removeById(fpKfId);
        if (removeFpKf) {
            return R.ok();
        } else {
            return R.error("撤销失败");
        }
    }
}